#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
提示词测试命令行工具
支持在开发环境中快速测试和调试提示词
"""

import sys
import os
import argparse
import json

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from src.research_core.prompt_debugger import create_prompt_debugger


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="提示词测试工具")
    parser.add_argument("--prompt", "-p", type=str, help="要测试的提示词")
    parser.add_argument("--requirement", "-r", type=str, help="相关需求描述")
    parser.add_argument("--file", "-f", type=str, help="包含提示词的文件路径")
    parser.add_argument("--compare", "-c", type=str, help="要比较的提示词文件路径（多个文件用逗号分隔）")
    parser.add_argument("--save", "-s", type=str, help="保存测试结果的文件路径")
    parser.add_argument("--verbose", "-v", action="store_true", help="详细输出模式")
    
    args = parser.parse_args()
    
    # 创建调试器实例
    debugger = create_prompt_debugger()
    
    # 处理不同的命令
    if args.compare:
        # 比较模式
        handle_comparison(debugger, args)
    elif args.file:
        # 文件模式
        handle_file_mode(debugger, args)
    elif args.prompt:
        # 直接提示词模式
        handle_prompt_mode(debugger, args)
    else:
        # 显示帮助信息
        parser.print_help()


def handle_prompt_mode(debugger, args):
    """处理直接提示词模式"""
    print("提示词测试工具 - 直接模式")
    print("=" * 40)
    
    prompt = args.prompt
    requirement = args.requirement or ""
    
    print(f"提示词: {prompt}")
    if requirement:
        print(f"需求: {requirement}")
    print()
    
    # 执行测试
    test_result = debugger.test_prompt(prompt, requirement)
    
    # 显示结果
    display_test_result(test_result, args.verbose)
    
    # 保存结果
    if args.save:
        success = debugger.save_test_result(test_result, args.save)
        if success:
            print(f"\n测试结果已保存到: {args.save}")
        else:
            print(f"\n保存测试结果失败")


def handle_file_mode(debugger, args):
    """处理文件模式"""
    print("提示词测试工具 - 文件模式")
    print("=" * 40)
    
    # 读取文件内容
    try:
        with open(args.file, 'r', encoding='utf-8') as f:
            prompt = f.read().strip()
    except Exception as e:
        print(f"读取文件失败: {e}")
        return
    
    requirement = args.requirement or ""
    
    print(f"文件: {args.file}")
    print(f"提示词长度: {len(prompt)} 字符")
    if requirement:
        print(f"需求: {requirement}")
    print()
    
    # 执行测试
    test_result = debugger.test_prompt(prompt, requirement)
    
    # 显示结果
    display_test_result(test_result, args.verbose)
    
    # 保存结果
    if args.save:
        success = debugger.save_test_result(test_result, args.save)
        if success:
            print(f"\n测试结果已保存到: {args.save}")
        else:
            print(f"\n保存测试结果失败")


def handle_comparison(debugger, args):
    """处理比较模式"""
    print("提示词测试工具 - 比较模式")
    print("=" * 40)
    
    # 解析要比较的文件
    files = args.compare.split(',')
    prompts = []
    
    for file_path in files:
        file_path = file_path.strip()
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                prompt = f.read().strip()
                prompts.append(prompt)
            print(f"已加载: {file_path} ({len(prompt)} 字符)")
        except Exception as e:
            print(f"读取文件 {file_path} 失败: {e}")
            return
    
    requirement = args.requirement or ""
    
    if requirement:
        print(f"需求: {requirement}")
    print()
    
    # 执行比较
    comparison_result = debugger.compare_prompts(prompts, requirement)
    
    # 显示结果
    display_comparison_result(comparison_result, args.verbose)
    
    # 保存结果
    if args.save:
        try:
            with open(args.save, 'w', encoding='utf-8') as f:
                json.dump(comparison_result, f, ensure_ascii=False, indent=2)
            print(f"\n比较结果已保存到: {args.save}")
        except Exception as e:
            print(f"\n保存比较结果失败: {e}")


def display_test_result(test_result, verbose=False):
    """显示测试结果"""
    advanced_eval = test_result['advanced_evaluation']
    
    print("测试结果:")
    print(f"  基础评分: {test_result['basic_score']:.2f}")
    print(f"  综合评分: {advanced_eval['overall_score']:.2f}")
    
    if verbose:
        print("  详细评分:")
        print(f"    清晰度: {advanced_eval['clarity']:.2f}")
        print(f"    完整性: {advanced_eval['completeness']:.2f}")
        print(f"    具体性: {advanced_eval['specificity']:.2f}")
        print(f"    相关性: {advanced_eval['relevance']:.2f}")
        print(f"    结构化: {advanced_eval['structuredness']:.2f}")
        print(f"    ML评分: {advanced_eval['ml_score']:.2f}")
    
    print(f"  执行时间: {test_result['execution_time']:.2f}秒")
    
    # 显示调试建议（仅在非详细模式下显示）
    if not verbose:
        # 创建临时调试器以获取建议
        temp_debugger = create_prompt_debugger()
        debug_result = temp_debugger.interactive_debug(
            test_result['prompt'], 
            test_result['requirement']
        )
        suggestions = debug_result['debug_suggestions']
        
        if suggestions:
            print("  调试建议:")
            for i, suggestion in enumerate(suggestions[:3], 1):  # 只显示前3条建议
                print(f"    {i}. {suggestion}")
            if len(suggestions) > 3:
                print(f"    ... 还有 {len(suggestions) - 3} 条建议")


def display_comparison_result(comparison_result, verbose=False):
    """显示比较结果"""
    if "error" in comparison_result:
        print(f"比较失败: {comparison_result['error']}")
        return
    
    ab_results = comparison_result['ab_test_results']
    variants = ab_results.get('variants', {})
    
    print("比较结果:")
    print(f"  测试版本数: {len(variants)}")
    
    # 显示各版本结果
    for variant_name, variant_data in variants.items():
        print(f"  {variant_name}:")
        print(f"    综合得分: {variant_data['overall_score']:.2f}")
        
        if verbose:
            variant_results = variant_data['results']
            if 'accuracy' in variant_results:
                print(f"    准确性: {variant_results['accuracy']:.2f}")
            if 'consistency' in variant_results:
                print(f"    一致性: {variant_results['consistency']:.2f}")
            if 'efficiency' in variant_results:
                print(f"    效率: {variant_results['efficiency']:.2f}")
    
    best_variant = ab_results.get('best_variant', 'N/A')
    print(f"\n  最佳版本: {best_variant}")


if __name__ == "__main__":
    main()